package com.sojson.util.lock.config.redisson;

import java.io.IOException;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.sojson.util.cache.redis.RedisCacheUtilInterface;
import com.sojson.util.cache.redis.bean.DbRds;

/**
 * Redisson配置类<BR>
 * (如果出现了LEAK: hashedwheelTimer.release() was not called before it’s garbage-collected. Enable advanced leak)<BR>
 * 网上搜到的是因为内存不够大导致
 * 
 * @author liu
 * @date 2021-07-19
 */
@Configuration
public class RedissonConfig {

    /**
     * 对 Redisson 的使用都是通过 RedissonClient 对象
     * @return
     * @throws IOException
     */
    @Bean(destroyMethod = "shutdown") // 服务停止后调用 shutdown 方法。
    @ConditionalOnProperty(name = "so.redis.enabled", havingValue = "true")
    public RedissonClient redisson() throws IOException {
        // 1.创建配置
        Config config = new Config();

        // 获取第一个数据源
        DbRds dbRds = RedisCacheUtilInterface.dbs.get(0);
        // 2.根据 Config 创建出 RedissonClient 示例
        SingleServerConfig serverConfig = config.useSingleServer();
        // 添加密码
        serverConfig.setPassword(dbRds.getPassword());

        // 单机模式
        serverConfig.setAddress("redis://" + dbRds.getHost() + ":" + dbRds.getPort());

        // 集群模式
        // // 获取地址列表
        // String[] dbs = new String[CacheUtil.dbs.size()];
        // for (int i = 0; i < dbs.length; i++) {
        // DbRds db = CacheUtil.dbs.get(i);
        // dbs[i] = db.getHost() + ":" + db.getPort();
        // }
        // // 添加地址列表
        // config.useClusterServers().addNodeAddress(dbs);

        return Redisson.create(config);
    }

}